package flex.cc.order.manage.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;
import flex.cc.PublicUtil;
import flex.cc.basicinformation.entity.ServiceProviderEntity;
import flex.cc.order.manage.dto.order.OrderServiceProviderEntity;
import flex.cc.vehicle_svr.vo.ResponseVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import flex.cc.PubUtils;
import flex.cc.basicinformation.service.ChannelService;
import flex.cc.bdmap.service.impl.MasterpointsServiceImpl;
import flex.cc.order.manage.dao.OrderImgDao;
import flex.cc.order.manage.dto.order.OrderImgEntity;
import flex.cc.order.manage.dto.order.OrderMainEntity;
import flex.cc.order.manage.service.OrderImgService;
import flex.cc.order.manage.service.OrderMainService;
import flex.cc.util.IoUtil;
import flex.cc.vehicle_svr.model.Images;
import flex.cc.vehicle_svr.model.UpLoadImageModel;
import io.netty.util.internal.StringUtil;

/**
 * 
 * @author WANGCONG
 * 2021年9月6日下午4:57:48
 * @desc 服务单图像业务实现层
 */
@Service("orderImgService")
@Transactional(rollbackFor = Exception.class)
public class OrderImgServiceImpl extends ServiceImpl<OrderImgDao, OrderImgEntity> implements OrderImgService{
	
	private static final Logger logger = LoggerFactory.getLogger(OrderImgServiceImpl.class);
	
	@Resource
    private OrderImgDao orderImgDao;
	@Resource
	private OrderImgService orderImgService;
	@Resource
	private UploadImgService uploadImgService;
	@Resource
	private OrderMainService orderMainService;
	@Value("${pengda.uploadPath}")
    private String uploadPath;
	@Value("${pengda.prefix}")
    private String prefix;
	@Resource
	private ChannelService channelService;
	@Resource
	private RedisTemplate<String, Object> redisTemplate;

	/**
	 * 
	 * @author WANGCONG
	 * 2021年9月6日下午6:15:12
	 * @desc 服务单管理---图像信息查询
	 */
	@Override
	public List<OrderImgEntity> queryImgByOrderNo(String orderNo) {
		return orderImgDao.queryImgByOrderNo(orderNo);
	}

	/**
	 * 
	 * @author WANGCONG
	 * 2021年9月6日下午6:15:12
	 * @desc 图像信息保存
	 */
	@Override
	public void saveImg(OrderImgEntity img) {
		orderImgService.save(img);
	}

	/**
	 * 
	 *  @author WANGCONG
	 * @return 
	 *  @date 2021年9月7日上午09:31:18
	 *  @desc 下游回传，本地落库保存
	 */
	@Override
	@Transactional
	public Map<String, String> synImg(UpLoadImageModel imgModel) {
		// 返回信息
		Map<String, String> resultMap = new HashMap<>();
		String orderNo = imgModel.getOrderNo(); //救援单号
		if(redisTemplate.hasKey(orderNo)){
			resultMap.put("code", "1");
			resultMap.put("message", "救援单号不存在");
			return resultMap;
		}
		// 查询单号信息
		Map<String, Object> order_param = new HashMap<>();
		order_param.put("orderNo", orderNo);
		OrderMainEntity orderMain = orderMainService.getOneByParams(order_param);
		if(orderMain==null){
			redisTemplate.opsForValue().set(orderNo, orderNo, 10, TimeUnit.SECONDS);
			resultMap.put("code", "1");
			resultMap.put("msg", "救援单号不存在");
			return resultMap;
		}

		// 查询已经存在的图片，已存在的不再处理
		List<String> myImgs = orderImgDao.queryImgByUrl(imgModel);
		// 待处理的图片
		List<Images> images = imgModel.getImgs();
		// 需要回传上游的图片
		List<String> picUrls = new ArrayList<String>();
		//本地保存路径生成规则：救援单号_时分秒字符串
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HHmmss");
		String localPath = orderNo + "_" + simpleDateFormat.format(new Date());
		for(int i=0; i<images.size(); i++){
			Images image = images.get(i);
			String imgUrl = image.getImgUrl();
			if(myImgs.contains(imgUrl)) {
				logger.info("vehicleSvr/synImg 图片已存在:imgUrl=" + imgUrl);
			} else {
				logger.info("vehicleSvr/synImg 下载图片:imgUrl=" + imgUrl);
				String localUrl = "";
				// 下载图片
				if(!StringUtil.isNullOrEmpty(imgUrl)){
					String fileName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
					picUrls.add(prefix + "/" + localPath + "/" + fileName);
					// System.out.println("地址="+prefix + "/" + localPath + "/" + fileName);
					try {
						IoUtil.download(imgUrl, fileName, localPath);
					} catch (Exception e) {
						e.printStackTrace();
						resultMap.put("code", "1");
						resultMap.put("msg", "图片上传异常");
						return resultMap;
					}
					localUrl = "/" + localPath + "/" + fileName;
				}
				// 保存图片
				OrderImgEntity vo = new OrderImgEntity();
				vo.setDataId(PubUtils.uuid());
				vo.setOrderNo(orderNo);
				vo.setImgType(image.getImgTypeId()+"");
				vo.setUrl(imgUrl);
				vo.setLocalUrl(localUrl);
				vo.setLongitude(image.getLongitude());
				vo.setLatitude(image.getLatitude());
				vo.setAddress(image.getAddress());
				vo.setCreateTime(new Date());
				vo.setUpdateTime(new Date());
				orderImgDao.insert(vo);
			}
		}
		//请求上游图片回传接口
		String sourceName = orderMain.getSourceName();  //渠道来源,00：自营、01：电话中心
		if(!"00".equals(sourceName) && picUrls.size() > 0){
			uploadImgService.uploadImg(orderNo, imgModel, orderMain.getOwnerOrderNo(), picUrls, sourceName, orderMain.getStatus());
		}
		resultMap.put("code", "0");
		resultMap.put("msg", "成功");
		return resultMap;
	}
	
}
